<template>
  <div class="wrap-container">
    <div class="card_left">
      <el-card>
        <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
          <div class="manage_tit">
            <div class="line"></div>
            <p>新建优惠券</p>
          </div>
          <div class="card_coupon">
            <div
              v-for="(dict, index) in dict?.type?.discount_type"
              :key="index"
              @click="handleTypeClick(dict)"
            >
              <div :class="['type_coupon', { active: form.discountType === dict.value }]">
                <div class="type_title">{{ dict.label }}</div>
                <div class="type_content">{{ dict.raw.remark }}</div>
              </div>
            </div>
            <div>
              <div class="type_coupon">
                <div class="type_title">更多优惠券</div>
                <div class="type_content">敬请期待</div>
              </div>
            </div>
          </div>
          <div class="divider"></div>
          <el-row :gutter="90">
            <el-col :span="12">
              <span class="form-title">*基本信息</span>
              <el-form-item label="优惠券名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请填写优惠券名称"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="渠道备注">
                <el-input
                  v-model="form.mname"
                  placeholder="请填写渠道备注"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="场馆备注">
                <el-input
                  v-model="form.bname"
                  placeholder="请填写场馆备注"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="发布渠道" prop="sourceType">
                <el-select
                  style="width: 100%"
                  filterable
                  clearable
                  v-model="form.sourceType"
                  placeholder="请选择发布渠道"
                  @change="changePlatformType"
                >
                  <el-option
                    v-for="dict in dict?.type?.platform_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="Number(dict.value)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="优惠券面值"
                prop="money.moneyType"
                v-if="form.discountType != '4'"
              >
                <div class="div_group">
                  <el-radio-group v-model="form.money.moneyType">
                    <el-radio label="1">
                      <el-input
                        style="width: 125px"
                        v-model="form.money.moneyAmount"
                        type="number"
                        placeholder="¥ 0.00"
                        clearable
                      />
                      <span class="ml-15px">元</span>
                    </el-radio>
                    <el-radio label="2">
                      <span class="mr-15px">满</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.money.moneyAmountGe"
                        type="number"
                        placeholder="最低金额"
                        clearable
                      />
                      <span class="ml-15px">元</span>
                      <span class="mx-15px">至</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.money.moneyAmountLe"
                        type="number"
                        placeholder="最高金额"
                        clearable
                      />
                      <span class="ml-15px">元</span>
                      <span class="ml-15px">可抵扣</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.money.moneyAmount"
                        type="number"
                        placeholder="抵扣金额"
                        clearable
                      />
                      <span class="ml-15px">元</span>
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>

              <el-form-item label="使用条件" prop="use.useType" v-if="form.discountType == '3'">
                <el-radio-group v-model="form.use.useType">
                  <el-radio label="1">无门槛</el-radio>
                  <el-radio label="2">
                    <span class="mr-15px">订单满</span>
                    <el-input
                      style="width: 125px"
                      v-model="form.use.useAmount"
                      type="number"
                      placeholder="最低金额"
                      clearable
                    />
                    <span class="ml-15px">元</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <span class="form-title" v-if="form.discountType == '4'">*卡券设置</span>

              <el-form-item
                label="卡券类型"
                prop="card.cardType"
                class="limit_item"
                v-if="form.discountType == '4'"
              >
                <el-radio-group
                  v-model="form.card.cardType"
                  :disabled="typeDisabled"
                  @change="handleCardRadioChange"
                >
                  <el-radio label="1">次卡</el-radio>
                  <el-radio label="2">周卡</el-radio>
                  <el-radio label="3">月卡</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="使用次数" prop="card.cardUseNum" v-if="form.discountType == '4'">
                <el-input
                  v-model="form.card.cardUseNum"
                  type="number"
                  placeholder="请填写使用次数"
                  clearable
                />
              </el-form-item>
              <el-form-item
                label="每天限次"
                prop="card.cardUseNumDay"
                v-if="form.discountType == '4'"
              >
                <el-input
                  v-model="form.card.cardUseNumDay"
                  type="number"
                  placeholder="请填写每天限次"
                  clearable
                />
              </el-form-item>
              <el-form-item label="其他说明">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 10 }"
                  placeholder="请输入优惠券相关说明（非必填项）"
                  v-model="form.remark"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <span class="form-title">*数量设置</span>
              <el-form-item label="优惠券数量" prop="total">
                <el-input
                  v-model="form.total"
                  type="number"
                  placeholder="请填写优惠券数量"
                  clearable
                />
              </el-form-item>
              <el-form-item label="领取限制" prop="limit.limitType">
                <el-radio-group v-model="form.limit.limitType">
                  <el-radio label="1">免费领取</el-radio>
                  <el-radio label="2">指定发放</el-radio>
                  <el-radio label="3">兑换领取</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="兑换设置" v-if="form.limit.limitType == '3'">
                <el-button type="primary" size="mini" @click="handleExchangeSetting"
                  >兑换设置</el-button
                >
              </el-form-item>
              <el-form-item label="每人限领" prop="limitUser.limitUserType">
                <el-radio-group v-model="form.limitUser.limitUserType">
                  <el-radio label="1">无限制</el-radio>
                  <el-radio label="2">
                    <el-input
                      style="width: 125px"
                      v-model="form.limitUser.limitUserTotal"
                      type="number"
                      placeholder="请填写每人限领"
                      clearable
                    />
                    <span class="ml-15px">张</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <span class="form-title">*有效期</span>
              <el-form-item prop="lifespan.lifespanType">
                <el-radio-group
                  v-model="form.lifespan.lifespanType"
                  :disabled="lifespanTypeDisabled"
                >
                  <el-radio label="1">
                    <span class="mr-15px">领券当日</span>
                    <el-input
                      style="width: 125px"
                      v-model="form.lifespan.lifespanDay"
                      type="number"
                      placeholder="请填写天数"
                      clearable
                    />
                    <span class="ml-15px">天有效</span>
                  </el-radio>
                  <el-radio label="2">
                    <el-date-picker
                      v-model="form.lifespan.lifespanStartTime"
                      type="date"
                      placeholder="开始日期"
                      value-format="yyyy-MM-dd"
                      @change="handleStartDateChange"
                    >
                    </el-date-picker>
                    <span class="mx-15px">至</span>
                    <el-date-picker
                      v-model="form.lifespan.lifespanEndTime"
                      type="date"
                      placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <span class="form-title">*适用范围</span>
              <el-form-item label="适用场馆" prop="applyStadium.applyStadiumType">
                <el-radio-group v-model="form.applyStadium.applyStadiumType">
                  <el-radio label="1">全部场馆</el-radio>
                  <el-radio label="2">指定场馆</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.applyStadium.applyStadiumType == '2'" label="选择场馆">
                <el-button type="primary" size="mini" @click="handleStadiumChange"
                  >选择场馆</el-button
                >
              </el-form-item>
              <el-form-item label="适用类型" prop="applySport.applySportType">
                <el-radio-group v-model="form.applySport.applySportType" :disabled="isDisabled">
                  <el-radio label="1">全部类型</el-radio>
                  <el-radio label="2">指定类型</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.applySport.applySportType == '2'" label="选择类型">
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleSportChange"
                  :disabled="isDisabled"
                  >选择类型</el-button
                >
              </el-form-item>

              <span class="form-title">使用限制</span>
              <el-form-item label="天数限用">
                <div class="div_group">
                  <el-radio-group
                    v-model="form.limitDayUse.limitDayType"
                    @change="handleLimitDayUseRadioChange"
                  >
                    <el-radio :label="''">无限制</el-radio>
                    <el-radio label="1">
                      <span class="mr-15px">每</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.limitDayUse.limitDayUseDays"
                        type="number"
                        placeholder="请填写天数"
                        clearable
                      />
                      <span class="ml-15px">天内可使用</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.limitDayUse.limitDayUseTotal"
                        type="number"
                        placeholder="请填写数量"
                        clearable
                      />
                      <span class="ml-15px">张</span>
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item label="天数限领">
                <div class="div_group">
                  <el-radio-group
                    v-model="form.limitDayReceive.limitDayReceiveType"
                    @change="handleLimitDayReceiveRadioChange"
                  >
                    <el-radio :label="''">无限制</el-radio>
                    <el-radio label="1">
                      <span class="mr-15px">每</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.limitDayReceive.limitDayReceiveDays"
                        type="number"
                        placeholder="请填写天数"
                        clearable
                      />
                      <span class="ml-15px">天内可领取</span>
                      <el-input
                        style="width: 125px"
                        v-model="form.limitDayReceive.limitDayReceiveTotal"
                        type="number"
                        placeholder="请填写数量"
                        clearable
                      />
                      <span class="ml-15px">张</span>
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item label="时间限制">
                <el-radio-group
                  v-model="form.limitTime.limitTimeType"
                  @change="handleLimitTimeRadioChange"
                >
                  <el-radio :label="''">无限制</el-radio>
                  <el-radio label="1">指定时间段</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.limitTime.limitTimeType == '1'" label="不可用时间段">
                <el-button type="primary" size="mini" @click="handleTimeChange"
                  >选择时间段</el-button
                >
              </el-form-item>
              <el-form-item label="用户领取限制">
                <el-radio-group
                  v-model="form.limitConsumer.limitConsumerType"
                  @change="handleLimitConsumerRadioChange"
                >
                  <el-radio label="1">无限制</el-radio>
                  <el-radio label="2">指定用户</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.limitConsumer.limitConsumerType == '2'" label="选择用户">
                <el-button type="primary" size="mini" @click="handleUserChange">选择用户</el-button>
              </el-form-item>
              <el-form-item label="允许转赠">
                <el-radio-group v-model="form.gift.giftType" @change="handleGiftRadioChange">
                  <el-radio :label="''">不允许</el-radio>
                  <el-radio label="1">允许</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="footer">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button type="primary" @click="saveForm" class="save_btn">保存</el-button>
            <el-button @click="handleClose">取消</el-button>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 兑换设置弹框 -->
    <exchange-setting
      v-if="exchangeSetting"
      ref="exchangeSettingRef"
      @refreshShow="handleRefreshShow"
    ></exchange-setting>
    <!-- 选择场馆 -->
    <choose-stadium
      v-if="chooseStadium"
      ref="chooseStadiumRef"
      @refreshShow="handleRefreshShow"
    ></choose-stadium>
    <!-- 运动类型 -->
    <choose-motion-type
      v-if="chooseMotionType"
      ref="chooseMotionTypeRef"
      @refreshShow="handleRefreshShow"
    ></choose-motion-type>
    <!-- 选择时间段 -->
    <choose-time
      v-if="chooseTime"
      ref="chooseTimeRef"
      @refreshShow="handleRefreshShow"
    ></choose-time>
    <!-- 选择用户 -->
    <choose-user
      v-if="chooseUser"
      ref="chooseUserRef"
      @refreshShow="handleRefreshShow"
    ></choose-user>
    <warn-dialog :visible="showTipVisible">
      <template #top>
        <span>发放数量不匹配</span>
      </template>
      <template #content>
        <p>
          当前设置将导致<span class="text-color-D43030">{{ remainNum }}</span
          >张券无法被完整领取。
        </p>
      </template>
      <template #button>
        <el-button type="primary" @click="showTipVisible = false">知道了</el-button>
      </template>
    </warn-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { addCoupons } from '@/api/coupon/coupon'
import { getRedis, addRedis } from '@/api/common/sysCommon'
import ExchangeSetting from './common/exchangeSetting.vue'
import ChooseStadium from './common/chooseStadium.vue'
import ChooseMotionType from './common/chooseMotionType.vue'
import ChooseTime from './common/chooseTime.vue'
import ChooseUser from './common/chooseUser.vue'
import { debounce } from '@/utils'
import { approvalSiteByStadiumId } from '@/api/site/site'
import WarnDialog from '../../components/common/warnDialog.vue'

// 字典数据
const { dict } = useDict({
  dicts: ['site_type', 'discount_type', 'platform_type', 'sys_normal_disable'],
})

// 定义响应式数据
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance | null>(null)
const exchangeSettingRef = ref<InstanceType<typeof ExchangeSetting> | null>(null)
const chooseStadiumRef = ref<InstanceType<typeof ChooseStadium> | null>(null)
const chooseMotionTypeRef = ref<InstanceType<typeof ChooseMotionType> | null>(null)
const chooseTimeRef = ref<InstanceType<typeof ChooseTime> | null>(null)
const chooseUserRef = ref<InstanceType<typeof ChooseUser> | null>(null)

const isDisabled = ref(false)
const typeDisabled = ref(false)
const exchangeSetting = ref(false)
const chooseStadium = ref(false)
const chooseMotionType = ref(false)
const chooseTime = ref(false)
const chooseUser = ref(false)
const showTipVisible = ref(false)
const remainNum = ref(0) // 剩余数量
const lifespanTypeDisabled = ref(false)

const form = reactive({
  discountType: '3', // 优惠券类型
  name: null as string | null, // 优惠券名称
  mname: null as string | null, // m端名
  bname: null as string | null, // b端名
  total: null as number | null, // 优惠券数量
  sourceType: null as number | null, // 发布渠道
  use: {
    // 使用条件
    useType: '2',
    useAmount: 0.0, // 满减总额度
  },
  money: {
    // 面值类型
    moneyType: '1',
    moneyAmount: 0.0, // 折扣金额
    moneyAmountGe: 0.0, // 折扣金额大于等于
    moneyAmountLe: 0.0, // 折扣金额小于等于
  },
  card: {
    // 卡券类型
    cardType: '1',
    cardUseNum: 1, // 卡券使用次数
    cardUseNumDay: 1, // 卡券每天使用次数
  },
  lifespan: {
    // 有效期
    lifespanType: '1',
    lifespanStartTime: '', // 开始时间
    lifespanEndTime: '', // 结束时间
    lifespanDay: '0', // 天数
    lifespanDayNext: '0', // 次日
  },
  limit: {
    // 领取限制
    limitType: '1',
    batchNum: null as string | null, // 兑换码集合
  },
  limitUser: {
    // 每人限领
    limitUserType: '2',
    limitUserTotal: 1, // 每人总限领
  },
  applyStadium: {
    // 适用场馆类型
    applyStadiumType: '1',
    couponsApply: [] as number[], // 指定可用/不可用集合
  },
  applySport: {
    applySportType: '1',
    couponsApply: [] as number[], // 指定可用/不可用集合
  },
  limitDayUse: {
    // 天数限用
    limitDayType: '',
    limitDayUseDays: '', // 天数限用 总天数
    limitDayUseTotal: '', // 天数限用 总数量
  },
  limitDayReceive: {
    // 天数限领
    limitDayReceiveType: '',
    limitDayReceiveDays: '', // 天数限领 总天数
    limitDayReceiveTotal: '', // 天数限领 总数量
  },
  limitTime: {
    // 时间限制
    limitTimeType: '',
    limitStartTime: '', // 开始时间
    limitEndTime: '', // 结束时间
  },
  limitConsumer: {
    // 用户领取限制
    limitConsumerType: '1',
    couponsApply: [] as number[], // 指定用户可领取集合
  },
  gift: {
    // 允许转赠
    giftType: '',
  },
  remark: null as string | null, // 其他说明
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请填写优惠券名称', trigger: 'change' }],
  total: [{ required: true, message: '请填写优惠券数量', trigger: 'change' }],
  sourceType: [{ required: true, message: '请选择发布渠道', trigger: 'change' }],
  'use.useType': [{ required: true, message: '请选择使用条件', trigger: 'change' }],
  'money.moneyType': [{ required: true, message: '请选择优惠券面值', trigger: 'change' }],
  'card.cardType': [{ required: true, message: '请选择卡券类型', trigger: 'change' }],
  'card.cardUseNum': [{ required: true, message: '请填写使用次数', trigger: 'change' }],
  'card.cardUseNumDay': [{ required: true, message: '请填写每天限次', trigger: 'change' }],
  'lifespan.lifespanType': [{ required: true, message: '请选择有效期', trigger: 'change' }],
  'limit.limitType': [{ required: true, message: '请选择领取限制', trigger: 'change' }],
  'limitUser.limitUserType': [{ required: true, message: '请选择每人限领', trigger: 'change' }],
  'applyStadium.applyStadiumType': [
    { required: true, message: '请选择适用场馆', trigger: 'change' },
  ],
})

onMounted(() => {
  if (route.query.data) {
    form = route.query.data
  } else {
    loadRedis()
  }
})

// 加载redis缓存
const loadRedis = () => {
  if (localStorage.getItem('couponsDraft')) {
    getRedis({ key: localStorage.getItem('couponsDraft') }).then((res: any) => {
      ElMessageBox.confirm(`有历史草稿数据，是否要使用？`)
        .then(() => {
          Object.assign(form, JSON.parse(res.msg))
        })
        .catch(() => {})
    })
  }
}

// 类型选中变色
const handleTypeClick = (dict: any) => {
  form.discountType = dict.value
  if (dict.value == '4') {
    form.lifespan.lifespanType = '2'
    form.lifespan.lifespanStartTime = ''
    form.lifespan.lifespanEndTime = ''
    lifespanTypeDisabled.value = true
  } else {
    form.card.cardType = '1'
    lifespanTypeDisabled.value = false
  }
}

// 选择平台类型
const changePlatformType = (val: number) => {
  isDisabled.value = val == 2 || val == 3 ? true : false
  typeDisabled.value = val == 3 ? true : false
  if (val == 0) {
    // @ts-ignore
    rules.motionType = []
    // @ts-ignore
    rules.siteName = []
  } else {
    // @ts-ignore
    rules.motionType = [{ required: true, message: '请选择运动类型', trigger: 'change' }]
    // @ts-ignore
    rules.siteName = [{ required: true, message: '请选择场地', trigger: 'change' }]
  }
}

// 兑换设置
const handleExchangeSetting = () => {
  exchangeSetting.value = true
  exchangeSettingRef.value?.init(form.total)
}

// 选择场馆
const handleStadiumChange = () => {
  chooseStadium.value = true
  const stadiumArr = form.applyStadium.couponsApply.map((id: number) => ({
    id,
  }))
  if (chooseStadiumRef.value) {
    chooseStadiumRef.value.selectData = stadiumArr
    chooseStadiumRef.value.init()
  }
}

// 选择运动类型
const handleSportChange = () => {
  chooseMotionType.value = true
  if (chooseMotionTypeRef.value) {
    chooseMotionTypeRef.value.checkList = form.applySport.couponsApply
    chooseMotionTypeRef.value.init()
  }
}

// 选择时间段
const handleTimeChange = () => {
  chooseTime.value = true
  if (chooseTimeRef.value) {
    chooseTimeRef.value.form.startTime = form.limitTime.limitStartTime
    chooseTimeRef.value.form.endTime = form.limitTime.limitEndTime
    chooseTimeRef.value.init()
  }
}

// 选择用户
const handleUserChange = () => {
  chooseUser.value = true
  const userArr = form.limitConsumer.couponsApply.map((id: number) => ({
    id,
  }))
  if (chooseUserRef.value) {
    chooseUserRef.value.selectData = userArr
    chooseUserRef.value.init()
  }
}

// 刷新显示
const handleRefreshShow = (val: any) => {
  exchangeSetting.value = false
  chooseStadium.value = false
  chooseMotionType.value = false
  chooseUser.value = false
  switch (val.type) {
    case 'exchangeSetting':
      if (val.total) {
        form.total = val.total
      }
      if (val.batchNum) {
        form.limit.batchNum = val.batchNum
      }
      break
    case 'chooseStadium':
      form.applyStadium.couponsApply = val.applyStadium
      break
    case 'chooseMotionType':
      form.applySport.couponsApply = val.applySport
      break
    case 'chooseTime':
      form.limitTime.limitStartTime = val.limitStartTime
      form.limitTime.limitEndTime = val.limitEndTime
      break
    case 'chooseUser':
      form.limitConsumer.couponsApply = val.couponsApply
      break
    default:
      break
  }
}

// 提交
const handleSubmit = debounce(
  () => {
    try {
      if (!formRef.value) return
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (form.limitConsumer.limitConsumerType == '2' && form.limitUser.limitUserType == '2') {
            // @ts-ignore
            remainNum.value = form.total % form.limitUser.limitUserTotal
          }
          if (remainNum.value > 0) {
            showTipVisible.value = true
            return
          }
          if (form.discountType == '4') {
            form.limitConsumer.limitConsumerType = '1'
            form.limitConsumer.couponsApply = []
          }
          await addCoupons(form).then((res: any) => {
            ElMessage.success(res.msg)
            router.go(-1)
          })
        }
      })
    } catch (e) {
      ElMessage.error((e as Error) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 保存
const saveForm = () => {
  ElMessageBox.confirm(`是否保存为草稿？`)
    .then(() => {
      const params = {
        value: form,
        // expire: 1140
      }
      return addRedis(params).then((res: any) => {
        localStorage.setItem('couponsDraft', res.msg)
      })
    })
    .then(() => {
      ElMessage.success('操作成功')
    })
    .catch(() => {})
}

// 取消
const handleClose = () => {
  router.go(-1)
}

// 天数限用单选处理
const handleLimitDayUseRadioChange = (e: string) => {
  // @ts-ignore
  e == form.limitDayUse.limitDayType
    ? (form.limitDayUse.limitDayType = '')
    : (form.limitDayUse.limitDayType = e)
}

// 天数限领单选处理
const handleLimitDayReceiveRadioChange = (e: string) => {
  // @ts-ignore
  e == form.limitDayReceive.limitDayReceiveType
    ? (form.limitDayReceive.limitDayReceiveType = '')
    : (form.limitDayReceive.limitDayReceiveType = e)
}

// 时间限制单选处理
const handleLimitTimeRadioChange = (e: string) => {
  // @ts-ignore
  e == form.limitTime.limitTimeType
    ? (form.limitTime.limitTimeType = '')
    : (form.limitTime.limitTimeType = e)
}

// 用户领取限制单选处理
const handleLimitConsumerRadioChange = (e: string) => {
  // @ts-ignore
  e == form.limitConsumer.limitConsumerType
    ? (form.limitConsumer.limitConsumerType = '')
    : (form.limitConsumer.limitConsumerType = e)
}

// 赠送单选处理
const handleGiftRadioChange = (e: string) => {
  // @ts-ignore
  e == form.gift.giftType ? (form.gift.giftType = '') : (form.gift.giftType = e)
}

// 卡券类型单选处理
const handleCardRadioChange = (e: string) => {
  // @ts-ignore
  e == form.card.cardType ? (form.card.cardType = '') : (form.card.cardType = e)
  if (e == '2') {
    form.lifespan.lifespanType = '2'
    lifespanTypeDisabled.value = true
    if (form.lifespan.lifespanStartTime && form.lifespan.lifespanStartTime != '') {
      // 计算时间往后推迟7天
      form.lifespan.lifespanEndTime = handleDateChange(form.lifespan.lifespanStartTime, 6)
    }
  } else if (e == '3') {
    form.lifespan.lifespanType = '2'
    lifespanTypeDisabled.value = true
    if (form.lifespan.lifespanStartTime && form.lifespan.lifespanStartTime != '') {
      // 计算时间往后推迟30天
      form.lifespan.lifespanEndTime = handleDateChange(form.lifespan.lifespanStartTime, 29)
    }
  }
}

// 时间选择
const handleStartDateChange = (val: string) => {
  if (form.discountType == '4') {
    if (form.card.cardType == '2') {
      console.log(val)
      // 计算时间往后推迟7天
      form.lifespan.lifespanEndTime = handleDateChange(val, 6)
    } else if (form.card.cardType == '3') {
      console.log(val)
      // 计算时间往后推迟30天
      form.lifespan.lifespanEndTime = handleDateChange(val, 29)
    }
  }
}

// 日期计算
const handleDateChange = (dateStr: string, days: number) => {
  const date = new Date(dateStr)
  date.setHours(0, 0, 0, 0)
  date.setDate(date.getDate() + days)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style lang="scss" scoped>
:deep(.el-card) {
  height: calc(100vh - 80px);
  overflow-y: auto;
}
:deep(.el-card__body) {
  padding-right: 84px;
}
.card_left {
  .card_coupon {
    display: flex;
    margin-top: 15px;
  }

  .type_coupon {
    cursor: pointer;
    width: 206px;
    height: 118px;
    padding: 20px;
    border-radius: 9px;
    background-color: rgba(241, 247, 255, 1);
    text-align: center;
    margin: 0 15px 0 0;

    .type_title {
      font-size: 16px;
      font-weight: 500;
      color: rgba(56, 56, 56, 1);
      margin: 0 0 20px 0;
    }

    .type_content {
      font-size: 14px;
      font-weight: 400;
      color: rgba(128, 128, 128, 1);
    }

    &.active {
      background-color: rgba(9, 136, 251, 1);

      .type_title {
        color: rgba(255, 255, 255, 1);
      }

      .type_content {
        color: rgba(255, 255, 255, 1);
      }
    }
  }

  .divider {
    margin: 15px 0;
    opacity: 1;
    height: 1px;
    background: #e5e5e5;
  }

  .form-title {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: rgba(42, 130, 228, 1);
    margin-bottom: 15px;
  }

  .div_group {
    margin: 0 0 15px 0;
  }

  .divider_text {
    font-size: 14px;
    font-weight: 400;
    color: rgba(42, 130, 228, 1);
  }

  .button_group {
    font-size: 14px;
    font-weight: 400;
  }
}

.card_right {
  margin: 0 0 0 20px;
}

.footer {
  text-align: center;
  margin-top: 22px;
  .el-button {
    width: 70px;
    height: 35px;
    border-radius: 8px;
    & + .el-button {
      margin-left: 14px;
    }
  }
  .save_btn {
    background: rgba(255, 141, 26, 1);
    border-color: rgba(255, 141, 26, 1);
  }
}
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 15px;
    &.limit_item {
      margin-bottom: 0;
      .div_group {
        margin-bottom: 8px;
      }
    }
    .radio_item {
      margin-bottom: 0;
    }
  }
  .el-form-item__label {
    padding-right: 19px;
  }
  .el-icon--right {
    margin-left: 0;
  }
}
:deep(.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner) {
  outline: none;
  box-shadow: none;
}
</style>
